/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/commons/json/serializer/CollectionSerializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: CollectionSerializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.serializer;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashSet;
import java.util.TreeSet;

/**
 * @author elancom
 */
public class CollectionSerializer implements ObjectSerializer {

	public final static CollectionSerializer instance = new CollectionSerializer();

	@Override
	public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
		final SerializeWriter out = serializer.getWriter();

		if (object == null) {
			if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) {
				out.write("[]");
			} else {
				out.writeNull();
			}
			return;
		}

			
		// {stduents:[{1...P{}.},{2...}]}
		
		Type elementType = null;
		if (serializer.isEnabled(SerializerFeature.WriteClassName)) {
			if (fieldType instanceof ParameterizedType) {
				final ParameterizedType param = (ParameterizedType) fieldType;
				elementType = param.getActualTypeArguments()[0];
			}
		}

		final Collection<?> collection = (Collection<?>) object;

		final SerialContext context = serializer.getContext();
		serializer.setContext(context, object, fieldName);

		if (serializer.isEnabled(SerializerFeature.WriteClassName)) {
			if (HashSet.class == collection.getClass()) {
				out.append("Set");
			} else if (TreeSet.class == collection.getClass()) {
				out.append("TreeSet");
			}
		}

		try {
			int i = 0;
			out.append('[');
			for (final Object item : collection) {

				if (i++ != 0) {
					out.append(',');
				}

				if (item == null) {
					out.writeNull();
					continue;
				}

				final Class<?> clazz = item.getClass();

				if (clazz == Integer.class) {
					out.writeInt(((Integer) item).intValue());
					continue;
				}

				if (clazz == Long.class) {
					out.writeLong(((Long) item).longValue());

					if (out.isEnabled(SerializerFeature.WriteClassName)) {
						out.write('L');
					}
					continue;
				}

				final ObjectSerializer itemSerializer = serializer.getObjectWriter(clazz);

				itemSerializer.write(serializer, item, i - 1, elementType);
			}
			out.append(']');
		} finally {
			serializer.setContext(context);
		}
	}

}
